<script setup lang="ts">
import { ref } from 'vue'
import { notification } from 'ant-design-vue'
import { cloneDeep } from 'lodash'
import SalesForm from './sales-form.vue'
import CustomerForm from '@/pages/customer/components/customer-form.vue'
import type { SalesDetailItem } from '@/api/sales/sales-list.ts'
import { addSalesDetailItem, updateSalesDetailItem } from '@/api/sales/sales-list.ts'
import { Dayjs } from 'dayjs'
import dayjs from 'dayjs'

const emit = defineEmits(['salesItemSave', 'cancel', 'ok'])

let value1 = ref<Dayjs>()

const isUpdate = ref(false)

const visible = ref(false)
const title = computed(() => {
  return isUpdate.value ? '编辑销售明细' : '新增销售明细'
})
function SalesItemSave() {
  console.log(`保存成功，返回刷新触发逻辑`)
}

// 销售明细对象
const formState = ref<SalesDetailItem>({
  sdiId: 0, // 销售明细ID
  salesId: 0, // 销售单ID
  productId: 0, // 产品ID
  sdiQuantity: 0, // 销售数量
  sdiPrice: 0, // 销售单价
  totalPrice: 0, // 销售总价
  sdiActualAmount: 0, // 实际销售金额
  sdiCostUnitPrice: 0, // 采购单价（成本单价）
  sdiFullCostPrice: 0, // 销售成本总价
  sdiPureProfit: 0, // 销售纯利润
  customerId: 0, // 客户ID
})

const salesForm = ref<InstanceType<typeof SalesForm>>()

// 获取产品选中id
function productSelected(cbdj: number, productId: number) {
  console.log(`当前选中的产品ID是：${productId}`)
  console.log(`当前选中的产品成本单价是：${cbdj}`)
  formState.value.productId = productId
  formState.value.sdiCostUnitPrice = cbdj
}

const customerForm = ref<InstanceType<typeof CustomerForm>>()
function customerSelected(customerId: number) {
  console.log(`当前选中的客户ID是：${customerId}`)
  formState.value.customerId = customerId
}

let purchaseId = ref(0)

// 打开对话框
function open(record: SalesDetailItem, id: number) {
  purchaseId.value = id
  console.log('打开销售明细操作弹框，关联编号：', record?.salesId)
  // 设定弹框显示添加项
  visible.value = true
  isUpdate.value = !!record?.sdiId // 销售明细编号
  formState.value = cloneDeep(record)
}

// 确定 处理编辑或添加
async function handleOk() {
  try {
    // 如果是编辑，则进入编辑调用接口
    if (isUpdate.value) {
      const res = await updateSalesDetailItem(formState.value)
      if (res.code === 200) {
        notification.success({
          message: '修改完成',
          duration: 3,
        })
        visible.value = false
      }
      else {
        notification.error({
          message: res.msg,
          duration: 3,
        })
      }
      visible.value = false
    }
    else {
      console.log(`当前选择的日期是1：${ formState.value.sdiDate }`)
      if (formState.value.sdiDate === "" || formState.value.sdiDate == undefined){
        console.log(`当前选择的日期是2：${ value1.value }`)
        formState.value.sdiDate = dayjs(value1.value).format('YYYY-MM-DD')
      }
      const res = await addSalesDetailItem(formState.value)
      if (res.code === 200) {
        notification.success({
          message: '添加成功',
          duration: 3,
        })
        visible.value = false
      }
      else {
        notification.error({
          message: res.msg,
          duration: 3,
        })
      }
    }
  }
  catch (e) {
    console.log(e)
  }
}

// 关闭对话框后操作
function cancelModal() {
  console.log('cancel')
}

function setUnitsToZeroAndRemoveDecimal(num: number): number {
  // 获取整数部分
  const integerPart = Math.floor(num);
  // 将整数部分的个位数设置为 0
  const result = Math.floor(integerPart / 10) * 10;
  // 返回结果
  return result;
}

// 计算销售自动总价
function onTotalPriceChange() {
  // 销售数量*销售单价=销售自动总价
  if (formState.value.sdiQuantity > 0 || formState.value.sdiPrice > 0 || formState.value.sdiCostUnitPrice > 0 || formState.value.sdiActualAmount > 0) {
    // 销售总价=销售数量*销售单价
    formState.value.totalPrice = formState.value.sdiQuantity * formState.value.sdiPrice
    // 销售成本总价=销售数量*采购单价
    formState.value.sdiFullCostPrice = formState.value.sdiQuantity * formState.value.sdiCostUnitPrice
    // 销售实际总价
    formState.value.sdiActualAmount = setUnitsToZeroAndRemoveDecimal(formState.value.totalPrice)
    // 销售纯利润=销售总价-销售成本总价
    formState.value.sdiPureProfit = formState.value.sdiActualAmount - formState.value.sdiFullCostPrice
    console.log(`销售纯利润：${formState.value.sdiPureProfit}`)
    console.log(`实际总金额：${formState.value.sdiActualAmount}`)
    console.log(`成本总价：${formState.value.sdiFullCostPrice}`)

  }
}
// 发车日期格式化
function onPDChange(value, dateString) {
  // value1 = value
  if (dateString !=''){
    formState.value.sdiDate = dayjs(dateString).format('YYYY-MM-DD')
    console.log(`当前选择的日期是：${formState.value.sdiDate}`)
  }
}
// 设定加载客户的类型是2 客户类型，1采购客户，2销售客户
const customerType=ref(2)
defineExpose({
  open,
})
</script>

<template>
  <a-modal v-model:open="visible" width="800px" :title="title" @ok="handleOk" @cancel="cancelModal">
    <a-form :model="formState" name="basic" autocomplete="off">
      <a-form-item name="value1" :rules="[{ required: false, message: '请选择销售日期' }]" label="销售日期">
        <a-date-picker v-model:value="value1" format="YYYY-MM-DD" style="width: 100%" @change="onPDChange"/>
      </a-form-item>
      <a-form-item label="销售产品" name="productId" :rules="[{ required: true, message: '选择本次销售产品' }]">
        <SalesForm ref="salesForm" :purchaseId="purchaseId" v-model:value="formState.productId" @productSelected="productSelected"/>
      </a-form-item>
      <a-form-item label="销售数量(斤数)" name="sdiQuantity" :rules="[{ required: true, message: '请输入销售数量' }]">
        <a-input-number v-model:value="formState.sdiQuantity" :min="0" :step="0.1" string-mode @change="onTotalPriceChange"/>
      </a-form-item>
      <a-form-item label="销售单价" name="sdiPrice" :rules="[{ required: true, message: '请输入销售单价' }]">
        <a-input-number v-model:value="formState.sdiPrice" :min="0" :step="0.01" string-mode  @change="onTotalPriceChange"/>
      </a-form-item>
      <a-form-item label="销售自动总价" name="totalPrice" :rules="[{ required: true, message: '自动计算销售总价' }]">
        <a-input-number v-model:value="formState.totalPrice" :min="0" :step="0.01" string-mode readonly/>
      </a-form-item>
      <a-form-item label="销售实际总价" name="sdiActualAmount" :rules="[{ required: true, message: '请输入实际总价' }]">
        <a-input-number v-model:value="formState.sdiActualAmount" :min="0" :step="0.01" string-mode  @change="onTotalPriceChange"/>
      </a-form-item>
      <a-form-item label="采购单价（成本单价）" name="sdiCostUnitPrice" :rules="[{ required: true, message: '请输入采购单价（成本单价）' }]">
        <a-input-number v-model:value="formState.sdiCostUnitPrice" :min="0" :step="0.01" string-mode/>
      </a-form-item>
      <a-form-item label="成本总价" name="sdiFullCostPrice" :rules="[{ required: true, message: '请输入成本总价' }]">
        <a-input-number v-model:value="formState.sdiFullCostPrice" :min="0" :step="0.01" string-mode readonly/>
      </a-form-item>
      <a-form-item label="纯利润" name="sdiPureProfit" :rules="[{ required: true, message: '请输入纯利润' }]">
        <a-input-number v-model:value="formState.sdiPureProfit" :min="0" :step="0.01" string-mode readonly/>
      </a-form-item>
      <a-form-item label="销售客户" name="customerId" :rules="[{ required: true, message: '请选择销售所属客户' }]">
        <CustomerForm ref="customerForm" :customerType="customerType" v-model:value="formState.customerId" @customerSelected="customerSelected"/>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<style scoped lang="less">

</style>
